import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.ensemble import AdaBoostClassifier
from sklearn.metrics import accuracy_score, roc_curve, auc
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np

# 设置中文字体为黑体（需确保系统中安装了黑体字体）
plt.rcParams['font.sans-serif'] = ['SimHei']
# 解决负号显示问题
plt.rcParams['axes.unicode_minus'] = False


# 读取数据
df = pd.read_excel(r'C:\Users\Administrator\Desktop\信用卡精准营销模型.xlsx')

# 缺失值分析与处理
print("缺失值情况：")
print(df.isnull().sum())
# 假设这里采用均值填充数值型特征的缺失值
numerical_cols = df.select_dtypes(include=[np.number]).columns
for col in numerical_cols:
    mean_val = df[col].mean()
    df[col] = df[col].fillna(mean_val)
# 假设采用众数填充非数值型特征的缺失值
non_numerical_cols = df.select_dtypes(exclude=[np.number]).columns
for col in non_numerical_cols:
    mode_val = df[col].mode()[0]
    df[col] = df[col].fillna(mode_val)

# 特征值分析
print("\n特征值统计信息：")
print(df.describe())

# 相关性分析
corr = df.corr()
plt.figure(figsize=(10, 8))
sns.heatmap(corr, annot=True, cmap='coolwarm')
plt.title('特征相关性热力图')
plt.show()

# 绘制数值型特征的分布直方图
numerical_cols = df.select_dtypes(include=[np.number]).columns
for col in numerical_cols:
    plt.figure(figsize=(8, 4))
    sns.histplot(data=df, x=col, kde=True)
    plt.title(f'{col}分布直方图')
    plt.xlabel(col)
    plt.ylabel('频数')
    plt.show()

# 绘制分类特征的计数条形图
categorical_cols = df.select_dtypes(exclude=[np.number]).columns
for col in categorical_cols:
    plt.figure(figsize=(8, 4))
    sns.countplot(data=df, x=col)
    plt.title(f'{col}类别计数条形图')
    plt.xlabel(col)
    plt.ylabel('数量')
    plt.show()

# 提取特征变量和目标变量
X = df.drop(columns='响应')
y = df['响应']

# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=123)

# 模型训练
clf = AdaBoostClassifier(random_state=123)
clf.fit(X_train, y_train)

# 模型预测
y_pred = clf.predict(X_test)

# 构建评估数据框
evaluation_df = pd.DataFrame()
evaluation_df['预测值'] = list(y_pred)
evaluation_df['实际值'] = list(y_test)

# 计算准确率
accuracy = accuracy_score(y_test, y_pred)
print(f"\n模型的预测准确度为: {accuracy}")

# 查看预测概率
y_pred_proba = clf.predict_proba(X_test)

# 绘制ROC曲线
fpr, tpr, thres = roc_curve(y_test.values, y_pred_proba[:, 1])
plt.plot(fpr, tpr)
plt.title('ROC Curve')
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
plt.show()

# 计算AUC值
auc_value = auc(fpr, tpr)
print(f"模型的AUC值为: {auc_value}")

# 分析特征重要性
feature_importances = pd.DataFrame(clf.feature_importances_, index=X_train.columns, columns=['重要性']).sort_values('重要性', ascending=False)
print(feature_importances)

# 绘制特征重要性条形图
plt.figure(figsize=(10, 6))
sns.barplot(data=feature_importances, x='重要性', y=feature_importances.index)
plt.title('特征重要性条形图')
plt.xlabel('重要性得分')
plt.ylabel('特征')
plt.show()